package com.xbongbong.paas.toolbox.helper;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * Bean Validation 帮助类
 * @author zheng.li
 *
 */
public class ValidationHelper {
	
	private static Validator validator;

	static {  
		ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
		validator = vf.getValidator();  
	}  
     
	/**
	 * 
	 * @param t
	 * @throws ValidationException
	 * @author zheng.li
	 * @time 2017-6-6 上午11:07:39
	*/
	public static <T> void validate(T t) throws ValidationException {
		Set<ConstraintViolation<T>> set =  validator.validate(t);
		if(set.size()>0){  
			StringBuilder validateError = new StringBuilder();  
			for(ConstraintViolation<T> val : set){
				validateError.append(val.getMessage()).append("! ");
			}  
			throw new ValidationException(validateError.toString());
		}  
	}  
	

}	
